<?php

namespace app\bll;

use support\Db;

class UserLoginlog
{
    public function add(
        int $uid,
        string $username_phone,
        int $accounttype,
        int $status
    ) {
        return Db::table('frame_user_loginlog')
            ->insert([
                'uid'            => $uid,
                'username_phone' => $username_phone,
                'accounttype'    => $accounttype,
                'status'         => $status,
                'logintime'      => date('Y-m-d H:i:s'),
                'loginip'        => request()->getRealIp(),
            ]);
    }

    /**
     * 最后一次登录信息
     *
     * @param integer $uid
     * @return array
     */
    public function lastLoginInfo(string $uid): array
    {
        $data = Db::table('frame_user_loginlog')
            ->where('uid', '=', $uid)
            ->where('status', '=', 1)
            ->orderByDesc('id')
            ->first();
        return $data === null ? [] : get_object_vars($data);
    }

    /**
     * 是否达到连续出错次数 并且未达到解封时间
     *
     * @param string $userorphone
     * @param integer $type
     * @param integer $errorcount
     * @return void
     */
    public function continuousErrorCount(
        string $userorphone,
        int $type,
        int $errorcount,
        int $disablelogintime
    ) {
        $logs = Db::table('frame_user_loginlog')
            ->where('username_phone', $userorphone)
            ->where('accounttype', $type)
            ->limit($errorcount)
            ->orderBy('id', 'desc')
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();

        if (!$logs || count($logs) < $errorcount) {
            return false;
        }

        $statuses = array_column($logs, 'status');
        //同时存在正确和错误
        if (count(array_unique($statuses)) > 1) {
            return false;
        }

        //只有成功的 返回false
        if ($statuses[0] == 1) {
            return false;
        }

        $lastlogintime = $logs[0]['logintime'];

        return strtotime($lastlogintime) + $disablelogintime * 60 > time();
    }



    /**
     * 是否登录错误次数太多 锁定账号
     *
     * @param string $userorphone
     * @param integer $logintype
     * @return boolean
     */
    public function LoginErrorLock(string $userorphone, int $logintype): bool
    {
        $bllSyscnfSafe = new SyscnfSafe();
        $cnfsave       = $bllSyscnfSafe->find();
        if (
            $cnfsave
            && $cnfsave['loginerrcount'] > 0
            && $cnfsave['disablelogintime'] > 0
        ) {
            if ($this->continuousErrorCount(
                userorphone: $userorphone,
                type: $logintype,
                errorcount: $cnfsave['loginerrcount'],
                disablelogintime: $cnfsave['disablelogintime']
            )) {
                return true;
            }
        }
        return false;
    }
}
